package artid.com.arttogoa;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.RealTimeMessageAdapter;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.keeponrecord.ArtRecordActivity;
import artid.com.arttogoa.keeponrecord.GroupPhotoActivity;
import artid.com.arttogoa.parser.ArtistWorkInfoParse;
import artid.com.arttogoa.parser.AuthcertificationItem;
import artid.com.arttogoa.parser.ClasslistParse;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.parser.RealTimeMessageBean;
import artid.com.arttogoa.parser.UpdataSystemMessageParser;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.MD5;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.SendHxMessage_Utils;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.view.MyListView;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

/**
 * TODO<主页>
 * 
 * @author 熊彬
 * @data: 2016-2-23 下午5:12:01
 * @version: V1.0
 */
public class MainActivity extends BaseActivity implements OnClickListener {
	private MyListView listview;
	private ImageView unreadMessage_icon, headImg, IsAuth, sell_icon;
	private ScrollView mScrollView;
	private LinearLayout ysba, yszx, ysdt, sell_ll;
	private TextView native_place, good_at, record, university, trendsnum,
			newsnum, sell_tv, classes_tv;
	private RelativeLayout titleRLBtn, personal, realTimeMessageBtn;
	private ImageLoader mImageLoader;
	private LinearLayout dataNullLL;
	public static Boolean isRefreshPersonal = false;// 默认不刷新
	private Bitmap clipBitmap;// 剪裁之后的图片
	private String Bitmap64;// 剪裁之后的图片流
	private RealTimeMessageAdapter adapter;
	private List<RealTimeMessageBean> list;
	private static List<EMConversation> conversationList;
	public static Boolean isLogin = false;// 主要用户环信推送点击判断
	public static Map<String, String> PushMessage = null;
	public static String friendAvatar = null;// 环信头像
	private Boolean mainIsOpen = null;// 当前页面是否打开
	public static String isSystemPush = null;// 是否有未读系统消息 0为没有，1为有
	private String PhotoPath;// 剪裁之后的图片路径
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				// 环信会话列表得到后
				conversationList.clear();
				conversationList.addAll(loadConversationsWithRecentChat());
				if (adapter == null && conversationList != null
						&& conversationList.size() != 0) {
					dataNullLL.setVisibility(View.GONE);
					adapter = new RealTimeMessageAdapter(mContext,
							conversationList);
					listview.setAdapter(adapter);
				} else if (adapter != null && conversationList != null
						&& conversationList.size() != 0) {
					dataNullLL.setVisibility(View.GONE);
					adapter.notifyDataSetChanged();
				} else if (conversationList == null
						|| conversationList.size() == 0) {
					dataNullLL.setVisibility(View.VISIBLE);
					return;
				}
				break;
			case 2:
				// 提示环信消息Dialog显示
				List<EMMessage> list = new ArrayList<EMMessage>();
				list = (List<EMMessage>) msg.obj;
				try {
					if (mainIsOpen != null && mainIsOpen == true) {
						ArtWorkApp.showMessageDialog(list.get(list.size() - 1));
					}
				} catch (Exception e) {
					Log.d("log", "消息对话框显示错误：" + e);
				}
				break;
			default:
				break;
			}
		};
	};
	private String userPhone;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.example.artworkarta.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = MainActivity.this;
		// UmengUpdateAgent.update(this);
		// UmengUpdateAgent.setUpdateOnlyWifi(false);
		setContent(this, getIntent());
		initData();
		getPersonalMessage();
		ArtWorkApp.getInstance().exit();
		ArtWorkApp.getInstance().addActivity(this);// 推出登录的时候需要关闭、
		userPhone = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue("Phone", "");
//		setArtHeight();
		classlist();
		initCache();
	}
	

	private void initCache() {
		// TODO Auto-generated method stub
		String artCache = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.ART_CACHE + userPhone, "");
		if (!TextUtils.isEmpty(artCache)) {
			AlertUtils.AlertTwoBtnDialog(
					mContext,
					"还有未完成的备案，是否去完成备案申请？",
					"确定",
					"取消",
					MainActivity.this.getWindowManager().getDefaultDisplay()
							.getWidth(), new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							switch (arg0.getId()) {
							case R.id.tv_ok:
								MySharedPreferences.getMySharedPreferences(
										mContext).setValue(
										Cache.IS_CACHE + userPhone, "true");
								String cache = MySharedPreferences
										.getMySharedPreferences(mContext)
										.getValue(Cache.ART_CACHE + userPhone,
												"");
								JSONObject ob;
								try {
									ob = new JSONObject(cache);
									String updataType = ob
											.optString("updataType");
									MySharedPreferences.getMySharedPreferences(
											mContext).setValue(Cache.ART_TYPE,
											updataType);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								Intent intent1 = new Intent(MainActivity.this,
										GroupPhotoActivity.class);
								startActivity(intent1);
								AlertUtils.dismiss();
								break;
							case R.id.tv_no:
								// initCache();
								MySharedPreferences.getMySharedPreferences(
										mContext).setValue(
										Cache.IS_CACHE + userPhone, "false");
								MySharedPreferences.getMySharedPreferences(
										mContext).setValue(
										Cache.ART_CACHE + userPhone, "");
								// Intent intent2 = new
								// Intent(MainActivity.this,
								// GroupPhotoActivity.class);
								// startActivity(intent2);
								AlertUtils.dismiss();
								break;

							default:
								break;
							}
						}
					}).show();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mainIsOpen = true;
		refreshHxMessage();
		// 艺术家备案动态资讯数量和推送消息数量
		getworkArtMessage();
		getArtistWorkInfo();
		EMClient.getInstance().chatManager().addMessageListener(msgListener);
		if (isRefreshPersonal == true) {
			isRefreshPersonal = false;// 恢复状态
			getPersonalMessage();
		}
	}

	/**
	 * 
	 */
	private void initData() {
		// TODO Auto-generated method stub
		isLogin = true;
		list = new ArrayList<RealTimeMessageBean>();
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.MainActivity.receiver");
		registerReceiver(broadcastReceiver, filter);
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		rightMenu.setVisibility(View.VISIBLE);
		conversationList = new ArrayList<EMConversation>();
		listview = (MyListView) findViewById(R.id.Main_listview);
		ysba = (LinearLayout) findViewById(R.id.ll_ysba);
		ysdt = (LinearLayout) findViewById(R.id.ll_ysdt);
		yszx = (LinearLayout) findViewById(R.id.ll_yszx);
		sell_ll = (LinearLayout) findViewById(R.id.main_sell_ll);
		native_place = (TextView) findViewById(R.id.native_place);
		good_at = (TextView) findViewById(R.id.good_at);
		classes_tv = (TextView) findViewById(R.id.main_classes);
		university = (TextView) findViewById(R.id.university);
		trendsnum = (TextView) findViewById(R.id.trendsnum);
		newsnum = (TextView) findViewById(R.id.newsnum);
		sell_tv = (TextView) findViewById(R.id.main_sell_tv);
		record = (TextView) findViewById(R.id.record);
		headImg = (ImageView) findViewById(R.id.MainActivity_headImg);
		IsAuth = (ImageView) findViewById(R.id.MainActivity_IsAuth);
		sell_icon = (ImageView) findViewById(R.id.main_sell_icon);
		headImg.setOnClickListener(this);
		getworkArtMessage();
		mTittle.setText(AppUtil.getUser().getRealname());
		personal = (RelativeLayout) findViewById(R.id.personal_layout);
		dataNullLL = (LinearLayout) findViewById(R.id.Main_dataNullLL);
		personal.setOnClickListener(this);
		titleRLBtn = (RelativeLayout) findViewById(R.id.title_RightRL);
		titleRLBtn.setOnClickListener(this);
		unreadMessage_icon = (ImageView) findViewById(R.id.title_unreadMessage);
		ysba.setOnClickListener(this);
		ysdt.setOnClickListener(this);
		yszx.setOnClickListener(this);
		realTimeMessageBtn = (RelativeLayout) findViewById(R.id.Main_more_RealTimeMessageBtn);
		realTimeMessageBtn.setOnClickListener(this);
		mScrollView = (ScrollView) findViewById(R.id.scrollView);
		mScrollView.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mScrollView.fullScroll(ScrollView.FOCUS_UP);
			}
		});
		// 环信登录
		loginHX();
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				// 进入聊天页面
				SendHxMessage_Utils.goChat(mContext, conversationList.get(arg2)
						.getLastMessage());
			}
		});

		if (getIntent().getBooleanExtra("isHxNotification", false)) {
			// 判断是否为点击环信通知栏进入
			SendHxMessage_Utils
					.goChat(mContext, SendHxMessage_Utils.mEMMessage);
		}

		if (PushMessage != null) {
			// 友盟推送点击通知栏处理
			Intent intent;
			if ("1".equals(PushMessage.get("messtype"))) {
				// 回复
				intent = new Intent(mContext, ArtDynamicDetailActivity.class);
				intent.putExtra("id", PushMessage.get("art_id"));
				startActivity(intent);
			} else if ("0".equals(PushMessage.get("messtype"))) {
				// 系统消息
				intent = new Intent(mContext, BaseWebView_Activity.class);
				intent.putExtra("titleName", "系统消息");
				intent.putExtra("webURL", PushMessage.get("messurl"));
				intent.putExtra("type", "systemWebView");
				intent.putExtra("messageID", PushMessage.get("messid"));
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			} else if ("2".equals(PushMessage.get("messtype"))) {
				// 收款消息
				intent = new Intent(mContext, OrderInfo_Activity.class);
				intent.putExtra("whichActivity", 1);
				intent.putExtra("order_id", PushMessage.get("art_id"));
				intent.putExtra("isPush", true);
				startActivity(intent);
			} else if ("4".equals(PushMessage.get("messtype"))) {
				// 订单已签收消息
				intent = new Intent(mContext, OrderInfo_Activity.class);
				intent.putExtra("whichActivity", 4);
				intent.putExtra("order_id", PushMessage.get("art_id"));
				intent.putExtra("isPush", true);
				startActivity(intent);
			} else if ("9".equals(PushMessage.get("messtype"))) {
				// 审核消息
				requestAutoStatus(PushMessage.get("messid"));
			}
		}
	}

	private Intent in;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_ysba:// 艺术家备案
			in = new Intent(MainActivity.this, ArtRecordActivity.class);
			startActivity(in);
			break;
		case R.id.ll_ysdt:// 艺术家动态
			in = new Intent(MainActivity.this, ArtDynamicActivity.class);
			startActivity(in);
			break;
		case R.id.ll_yszx:// 艺术家资讯
			in = new Intent(MainActivity.this, ArtConsultationActivity.class);
			startActivity(in);
			break;
		case R.id.main_sell_ll:// 艺术品出售
			in = new Intent(MainActivity.this, MySell_Activity.class);
			startActivity(in);
			break;
		case R.id.title_RightRL:// 个人中心
			in = new Intent(MainActivity.this, PersonalActivity.class);
			startActivity(in);
			break;
		case R.id.personal_layout:// 个人信息
			in = new Intent(MainActivity.this, PersonalMessageActivity.class);
			startActivity(in);
			break;
		case R.id.MainActivity_headImg:
			// 上传头像
			showAvatarPopupWindow();
			break;
		case R.id.Main_more_RealTimeMessageBtn:
			// 更多实时消息
			Intent i = new Intent(mContext, MessageActivity.class);
			startActivity(i);
			break;
		default:
			break;
		}
	}

	/**
	 * 得到个人信息
	 */
	private void getPersonalMessage() {
		String na = AppUtil.getUser().getPath();
		String name = MD5.getMD5(na) + na.substring(na.lastIndexOf("."));
		String path = Environment.getExternalStorageDirectory() + "/YJB/"
				+ name;
		String SharedPath = MySharedPreferences
				.getMySharedPreferences(mContext).getValue("HeadURL", "");
		// 判断本地保存的头像是否与服务器地址相同
		if (SharedPath.equals(path)) {
			Bitmap smallBitmap = BitmapUtil
					.getSmallFilletBitmap(path, 500, 500);
			if (smallBitmap != null) {
				headImg.setImageBitmap(smallBitmap);
			} else {
				downloadAndSaveHeadImage();
			}
		} else {
			downloadAndSaveHeadImage();
		}
		// 获取最新个人信息
		if (!StringUtils.isEmpty(AppUtil.getUser().getRealname())) {
			mTittle.setText(AppUtil.getUser().getRealname());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getNative_place())) {
			native_place.setText(AppUtil.getUser().getNative_place());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getNative_place())) {
			native_place.setText(AppUtil.getUser().getNative_place());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getGood_at())) {
			good_at.setText(AppUtil.getUser().getGood_at());
		}
		// 重新部署服务器之后删除本地获取分类
		if (!StringUtils.isEmpty(MySharedPreferences.getMySharedPreferences(
				mContext).getValue("Classes" + AppUtil.getUser().getUid(), ""))) {
			classes_tv.setText(MySharedPreferences.getMySharedPreferences(
					mContext).getValue("Classes" + AppUtil.getUser().getUid(),
					""));
		} else {
			if (!StringUtils.isEmpty(AppUtil.getUser().getAname())) {
				classes_tv.setText(AppUtil.getUser().getAname());
			}
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getUniversity())) {
			university.setText(AppUtil.getUser().getUniversity());
		}
		if (!StringUtils.isEmpty(AppUtil.getUser().getIs_auth())
				&& "1".equals(AppUtil.getUser().getIs_auth())) {
			// 是否认证
			IsAuth.setVisibility(View.VISIBLE);
			// 设置艺术品出售背景图片
			sell_icon.setBackgroundResource(R.drawable.home_sell_bg);
			sell_ll.setOnClickListener(this);
		} else {
			sell_icon.setBackgroundResource(R.drawable.zjm_btn_chushou_gray);
		}
	}

	/**
	 * 获取艺术品信息
	 */
	private void getworkArtMessage(){
		record.setText("艺术品备案\n(" + AppUtil.getUser().getRecordnum() + ")");
		trendsnum.setText("艺术家动态\n(" + AppUtil.getUser().getTrendsnum() + ")");
		newsnum.setText("艺术品资讯\n(" + AppUtil.getUser().getNewsnum() + ")");
		sell_tv.setText("艺术品出售\n(" + AppUtil.getUser().getGoodsnum() + ")");
	}

	// 点击头像，选择照片
	public void showAvatarPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext, Integer.parseInt(NetUtils
				.getDisplayMetrics(MainActivity.this).get(NetUtils.DM_WIDTH)),
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						switch (v.getId()) {
						case R.id.tv_phone:
							//检查权限
							if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
								displayFrameworkBugMessageAndExit();
								return;
							}
							// 照相机
							CameraUtils.openCameraImage(MainActivity.this);
							AlertUtils.dismiss();
							break;
						case R.id.tv_choice:
							// 从相册获取
							CameraUtils.openLocalImage(MainActivity.this);
							AlertUtils.dismiss();
							break;
						default:
							break;
						}
					}
				});
	}

	/**
	 * 上传头像
	 */
	private void submitphoto() {
		VolleyBasic.getInstance(MainActivity.this).post(Cache.headinfo,
				VolleyMap.getInstance().headInfo(Bitmap64), NormalItem.class,
				new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						NormalItem normalItem = (NormalItem) vd.getData();
						// 设置图片
						headImg.setImageBitmap(clipBitmap);
						String imgUrl = normalItem.data;
						AppUtil.getUser().setPath(imgUrl);
						try {
							// 保存头像
							String path = null;
							if (!StringUtils.isEmpty(imgUrl)) {
								String name = MD5.getMD5(imgUrl)
										+ imgUrl.substring(imgUrl
												.lastIndexOf("."));
								// 保存头像地址
								path = Environment
										.getExternalStorageDirectory()
										+ "/YJB/" + name;
							}
							BitmapUtil.saveBitmapToFile(clipBitmap, path);
							// 保存头像地址
							MySharedPreferences
									.getMySharedPreferences(mContext).setValue(
											"HeadURL", path);
							if (!StringUtils.isEmpty(PhotoPath)) {
								BitmapUtil.deleteBitmap(PhotoPath);
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						showToast("上传头像失败");
					}
				});

	}

	/**
	 * 下载并保存图片
	 */
	private void downloadAndSaveHeadImage() {
		if (!StringUtils.isEmpty(AppUtil.getUser().getAvatarurl())) {
			mImageLoader.get(AppUtil.getUser().getAvatarurl(),
					new ImageListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onResponse(ImageContainer response,
								boolean isImmediate) {
							// TODO Auto-generated method stub
							try {
								Bitmap head = response.getBitmap();
								if (head != null) {
									String imgUrl = AppUtil.getUser().getPath();
									// 保存头像
									String path = null;
									if (!StringUtils.isEmpty(imgUrl)) {
										String name = MD5.getMD5(imgUrl)
												+ imgUrl.substring(imgUrl
														.lastIndexOf("."));
										// 保存头像地址
										path = Environment
												.getExternalStorageDirectory()
												+ "/YJB/" + name;
										BitmapUtil.saveBitmapToFile(head, path);
										MySharedPreferences
												.getMySharedPreferences(
														mContext).setValue(
														"HeadURL", path);
									}
									headImg.setImageBitmap(BitmapUtil
											.toRoundCorner(head, 8));
								}
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			if (uri != null) {
				Intent i = new Intent(mContext, Clip_Activity.class);
				i.putExtra("ImagePath",
						BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			} else {
				// 防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@SuppressWarnings("unused")
					@Override
					public void run() {
						if (uri != null) {
							Intent i = new Intent(mContext, Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil
									.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			// 判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i = new Intent(mContext, Clip_Activity.class);
				i.putExtra("ImagePath",
						BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if (requestCode == 200) {
			// 获取剪切后的图片路径
			if (data != null) {
				PhotoPath = data.getExtras().getString("PhotoPath");
				if (!StringUtils.isEmpty(PhotoPath)) {
					clipBitmap = BitmapUtil.getSmallFilletBitmap(PhotoPath,
							500, 500);
					Bitmap64 = BitmapUtil.bitmaptoString(clipBitmap);
					submitphoto();
				}
			}
		}
	}

	/**
	 * 环信登陆
	 */
	int HxLoginNum = 0;// 登陆次数

	private void loginHX() {
		HxLoginNum++;
		Log.d("log", "环信登陆次数：" + HxLoginNum);
		if (HxLoginNum != 100) {
			EMClient.getInstance().login(AppUtil.getUser().getUid(),
					"yjbgp2016", new EMCallBack() {// 回调
						@Override
						public void onSuccess() {
							Activity activity = (Activity) mContext;
							activity.runOnUiThread(new Runnable() {
								public void run() {
									Log.d("log", "环信:登陆聊天服务器成功！");
									EMClient.getInstance().chatManager()
											.addMessageListener(msgListener);
								}
							});
						}

						@Override
						public void onProgress(int progress, String status) {
							Log.d("log", "环信:登陆中！");
						}

						@Override
						public void onError(int code, String message) {
							Log.d("log", "环信:登陆聊天服务器失败！");
							loginHX();
						}
					});
		}
	}

	/**
	 * 环信消息接收
	 */
	EMMessageListener msgListener = new EMMessageListener() {

		@Override
		public void onCmdMessageReceived(List<EMMessage> list_EMMessage) {
			// TODO Auto-generated method stub
			// 透传消息
			Log.d("log", "环信透传消息:" + list_EMMessage.toString());

		}

		@Override
		public void onMessageRead(List<EMMessage> list) {
			// 已读回执
		}

		@Override
		public void onMessageDelivered(List<EMMessage> list) {
			// 已送达
		}

		@Override
		public void onMessageChanged(EMMessage arg0, Object arg1) {
			// TODO Auto-generated method stub
			// 消息状态变动
		}


		@Override
		public void onMessageReceived(final List<EMMessage> list_EMMessage) {
			// TODO Auto-generated method stub
			// 收到消息
			Log.d("log", "环信消息:" + list_EMMessage.toString());
			refreshHxMessage();
			// 消息提示框
			Message msg = mHandler.obtainMessage(2, list_EMMessage);
			mHandler.sendMessage(msg);
		}
	};

	/**
	 * 刷新环信会话列表
	 */
	public void refreshHxMessage() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(1);
			}
		}).start();
	}

	/**
	 * 获取所有会话
	 * 
	 * @param context
	 * @return +
	 */
	private List<EMConversation> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Map<String, EMConversation> conversations = EMClient.getInstance()
				.chatManager().getAllConversations();
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
		 */
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					sortList.add(new Pair<Long, EMConversation>(conversation
							.getLastMessage().getMsgTime(), conversation));
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		for (int i = 0; i < list.size(); i++) {
			Log.d("log", "环信会话列表：" + list.get(i).getLastMessage().toString());
		}

		return list;
	}

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortConversationByLastChatTime(
			List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList,
				new Comparator<Pair<Long, EMConversation>>() {
					@Override
					public int compare(final Pair<Long, EMConversation> con1,
							final Pair<Long, EMConversation> con2) {

						if (con1.first == con2.first) {
							return 0;
						} else if (con2.first > con1.first) {
							return 1;
						} else {
							return -1;
						}
					}

				});
	}

	/**
	 * 艺术家备案动态资讯数量和推送消息数量
	 */
	private void getArtistWorkInfo() {
		VolleyBasic.getInstance(this).post(false, false, Cache.artistWorkInfo,
				VolleyMap.getInstance().artistWorkInfo(),
				ArtistWorkInfoParse.class, new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						Log.d("log", "艺术家备案动态资讯数量和推送消息数量：" + vd.getJson());
						ArtistWorkInfoParse bean = (ArtistWorkInfoParse) vd
								.getData();
						if (bean != null) {
							AppUtil.getUser().setRecordnum(bean.getRecordnum());
							AppUtil.getUser().setTrendsnum(bean.getTrendsnum());
							AppUtil.getUser().setNewsnum(bean.getNewsnum());
							AppUtil.getUser().setIs_auth(bean.getIs_auth());
							AppUtil.getUser().setGoodsnum(bean.getGoodsnum());
							isSystemPush = bean.getIs_pushread();
							record.setText("艺术品备案\n("
									+ AppUtil.getUser().getRecordnum() + ")");
							trendsnum.setText("艺术家动态\n("
									+ AppUtil.getUser().getTrendsnum() + ")");
							newsnum.setText("艺术品资讯\n("
									+ AppUtil.getUser().getNewsnum() + ")");
							sell_tv.setText("艺术品出售\n(" + AppUtil.getUser().getGoodsnum() + ")");
							if ("1".equals(isSystemPush)
									|| hxUnreadMessage() != 0
									|| "true".equals(MySharedPreferences
											.getMySharedPreferences(mContext)
											.getValue(
													"isReplyPush"
															+ AppUtil.getUser()
																	.getUid(),
													"false"))) {
								unreadMessage_icon.setVisibility(View.VISIBLE);
							} else {
								unreadMessage_icon.setVisibility(View.GONE);
							}
						}
					}

					@Override
					public void onError(VolleyError volleyError) {

					}

				});
	}

	/**
	 * 获取出售年代类别、作品分类、快递种类
	 */
	private void classlist() {
		VolleyBasic.getInstance(this).post(false, false, Cache.classlist,
				VolleyMap.getInstance().classlist(), ClasslistParse.class,
				new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						Log.d("log", "获取出售年代类别、作品分类、快递种类:" + vd.getJson());
						ClasslistParse bean = (ClasslistParse) vd.getData();
						DataKeeper.keepSerializable(mContext, bean);
					}

					@Override
					public void onError(VolleyError volleyError) {

					}

				});
	}

	/**
	 * 获取审核信息
	 */
	private void requestAutoStatus(final String messageID) {
		VolleyBasic.getInstance(MainActivity.this).post(true, false,
				Cache.authcertification,
				VolleyMap.getInstance().authCertification(),
				AuthcertificationItem.class, new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						AuthcertificationItem item = (AuthcertificationItem) vd
								.getData();
						String status = item.getIs_auth();
						// 更新审核信息
						AppUtil.getUser().setIs_auth(status);
						updataSystmeMessage(messageID, status);
					}

					@Override
					public void onError(VolleyError volleyError) {
					}
				});
	}

	/**
	 * 修改系统消息为已读
	 */
	private void updataSystmeMessage(final String MessageId, final String status) {
		VolleyBasic.getInstance(this).post(false, true, Cache.updateSystemread,
				VolleyMap.getInstance().updateSystemread(MessageId),
				UpdataSystemMessageParser.class, new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						System.out.println(vd.getJson());
						UpdataSystemMessageParser bean = (UpdataSystemMessageParser) vd
								.getData();
						if ("1".equals(bean.getStatus())) {
							if (status.equals("-1")) {
								// 未通过
								Intent intent = new Intent(mContext,
										RealNameAuthenticationActivity.class);
								intent.putExtra("isPush", true);
								intent.putExtra("messageID", MessageId);
								startActivity(intent);
							} else {
								Intent intent = new Intent(mContext,
										RealNameAuthenticationTwoActivity.class);
								intent.putExtra("isPush", true);
								intent.putExtra("messageID", MessageId);
								startActivity(intent);
							}
						} else if ("0".equals(bean.getStatus())) {
							// 失败
							ToastUtil.toast(mContext, "修改消息状态失败");
						}
					}

					public void onError(VolleyError volleyError) {
					}
				});
	}

	/**
	 * 友盟通知栏判断(暂时不需要)
	 */
	private void UmengNotificationJudge(String messtype, String art_id) {
		if ("1".equals(messtype)) {
			// 回复
			if (!ArtWorkApp.isForeground(mContext,
					"com.aicpsp.artworkarta.ArtDynamicDetailActivity")) {
				// 判断要打开的页面否已经打开
				Intent i = new Intent(mContext, ArtDynamicDetailActivity.class);
				i.putExtra("id", art_id);
				mContext.startActivity(i);
			}
		} else if ("0".equals(messtype)) {
			// 系统消息
			if (!ArtWorkApp.isForeground(mContext,
					"com.aicpsp.artworkarta.NoticeActivity")) {
				// 判断要打开的页面否已经打开
				Intent i = new Intent(mContext, NoticeActivity.class);
				mContext.startActivity(i);
			}
		}
	}

	/**
	 * 获取环信未读消息
	 * 
	 * @return
	 */
	public static int hxUnreadMessage() {
		int size = 0;
		if (conversationList != null) {
			for (int i = 0; i < conversationList.size(); i++) {
				EMConversation conversation = EMClient.getInstance()
						.chatManager()
						.getConversation(conversationList.get(i).conversationId());
				size = size + conversation.getUnreadMsgCount();
			}
		}
		return size;
	}

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}

	// 广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getBooleanExtra("UmengPush", false) == true) {
				// 友盟是否有消息(系统/收款/订单签收/消息/审核)
				if ("0".equals(intent.getStringExtra("PushType"))
						|| "2".equals(intent.getStringExtra("PushType"))
						|| "4".equals(intent.getStringExtra("PushType"))
						|| "9".equals(intent.getStringExtra("PushType"))) {
					isSystemPush = "1";// 设置有未读消息
					if ("9".equals(intent.getStringExtra("PushType"))) {
						// 如果是审核消息就通知审核页面刷新数据，这里是防止用户在审核页面的时候不刷新数据
						requestAutoStatus(PushMessage.get("messid"));
						Intent intent2 = new Intent(
								"com.RealNameAuthenticationTwoActivity.receiver");
						intent2.putExtra("UmengPush", true);
						intent2.putExtra("PushType",
								intent.getStringExtra("PushType"));
						mContext.sendBroadcast(intent2);
					}
				}
				unreadMessage_icon.setVisibility(View.VISIBLE);
			}
			if (intent.getBooleanExtra("HXPush", false) == true) {
				unreadMessage_icon.setVisibility(View.VISIBLE);
			}
			if (intent.getBooleanExtra("Push", false) == true) {
				UmengNotificationJudge(PushMessage.get("messtype"),
						PushMessage.get("art_id"));
			}

		}
	};

	// 再按一次退出程序
	long backPressTime;

	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {
			long current = System.currentTimeMillis();
			if (current - backPressTime > 2000) {
				backPressTime = current;
				ToastUtil.commonToast(mContext, "再次按返回键退出程序");
			} else {
				finish();
			}
			return false;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isLogin = false;
		mainIsOpen = null;
		// 清空推送
		MainActivity.PushMessage = null;
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}

}
